<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>一枚前端小菜鸟的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="本网站仅作为自己日常使用，如有侵权请告知删除，联系方式：1563831554@qq.com">
<meta property="og:type" content="website">
<meta property="og:title" content="一枚前端小菜鸟的博客">
<meta property="og:url" content="https://gitee.com/weiyayun1995/weiyayun1995.git/index.html">
<meta property="og:site_name" content="一枚前端小菜鸟的博客">
<meta property="og:description" content="本网站仅作为自己日常使用，如有侵权请告知删除，联系方式：1563831554@qq.com">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="yywei">
<meta property="article:tag" content="菜鸟,前端,js,react,vue">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="一枚前端小菜鸟的博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">一枚前端小菜鸟的博客</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">yywei的遇坑记录</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/weiyayun1995/weiyayun1995.git"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main">
  
    <article id="post-js数据类型及转换" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/" class="article-date">
  <time class="dt-published" datetime="2021-06-22T05:42:36.000Z" itemprop="datePublished">2021-06-22</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/">js数据类型及转换</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h5 id="下面代码输出结果"><a href="#下面代码输出结果" class="headerlink" title="下面代码输出结果"></a>下面代码输出结果</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>,<span class="number">2</span>] + [<span class="number">3</span>,<span class="number">4</span>]</span><br><span class="line">[] + &#123;&#125;</span><br><span class="line">&#123;&#125; + []</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. []和&#123;&#125;都是对象，因此调用toString()方法，&#x27;&#x27; + &#x27;[Object Object]&#x27;</span></span><br><span class="line"><span class="comment">// 2. &#123;&#125;es6中被认为是一个代码块，+[]表示正负数因此被强制转换成数字类型+0，所以结果是0</span></span><br></pre></td></tr></table></figure>
<h5 id="基本数据类型"><a href="#基本数据类型" class="headerlink" title="基本数据类型"></a>基本数据类型</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Undefined、Null、<span class="built_in">Boolean</span>、<span class="built_in">Number</span>、<span class="built_in">String</span>、<span class="built_in">Symbol</span></span><br></pre></td></tr></table></figure>
<p><img src="https://assets.che300.com/wiki/2021-05-18/16213164486292034.png"></p>
<h5 id="精度丢失的解决办法"><a href="#精度丢失的解决办法" class="headerlink" title="精度丢失的解决办法"></a>精度丢失的解决办法</h5><p>将小数放大到正数，再缩小为原来的倍数<br>例：(0.1<em>10 + 0.2</em>10) / 10</p>
<h5 id="再来看以下代码"><a href="#再来看以下代码" class="headerlink" title="再来看以下代码"></a>再来看以下代码</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log([] == [])</span><br><span class="line"><span class="built_in">console</span>.log([] == ![])</span><br><span class="line"><span class="built_in">console</span>.log([] !== [])</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">NaN</span> != <span class="literal">NaN</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">null</span> == <span class="literal">undefined</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">null</span> === <span class="literal">undefined</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">1</span> == <span class="literal">true</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">null</span> &gt; <span class="number">0</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">true</span> + <span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">undefined</span> + <span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log(&#123;&#125; + <span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log([] + &#123;&#125;)</span><br><span class="line"><span class="built_in">console</span>.log([<span class="number">2</span>,<span class="number">3</span>] + [<span class="number">1</span>,<span class="number">2</span>])</span><br></pre></td></tr></table></figure>

<h5 id="分析下列值分别对应转化为数字、字符串、布尔时的值"><a href="#分析下列值分别对应转化为数字、字符串、布尔时的值" class="headerlink" title="分析下列值分别对应转化为数字、字符串、布尔时的值"></a>分析下列值分别对应转化为数字、字符串、布尔时的值</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">false</span>,<span class="literal">true</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="string">&quot;0&quot;</span>,<span class="literal">NaN</span>,<span class="literal">Infinity</span>（表示无穷大）,<span class="string">&quot;&quot;</span>,[],&#123;&#125;,[<span class="number">0</span>],<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;,<span class="literal">null</span>,undefiend</span><br></pre></td></tr></table></figure>
<h5 id="对应值"><a href="#对应值" class="headerlink" title="对应值"></a>对应值</h5><p><img src="https://assets.che300.com/wiki/2021-05-09/16205717674285892.png"></p>
<h5 id="正负运算符"><a href="#正负运算符" class="headerlink" title="正负运算符"></a>正负运算符</h5><p>仅仅表示数字的正负，注意和+运算符的区分</p>
<h4 id="比较运算"><a href="#比较运算" class="headerlink" title="比较运算"></a>比较运算</h4><p>js为我们提供了严格比较与类型转换比较两种模式，严格比较(===)只会在操作符两侧的操作对象类型一致，并且内容一致时才会返回true，否则返回false。而更为广泛使用的==操作符则会首先将操作对象转化为相同类型，在进行比较。</p>
<ol>
<li><p><strong>相等操作符会对操作值进行隐式转换后进行比较：</strong><br>如果一个操作值为布尔值，则在比较之前先将其转换为数值<br>如果一个操作值为字符串，另一个操作值为数值，则通过Number()函数将字符串转换为数值<br>如果一个操作值是对象，另一个不是，则调用对象的valueOf()方法，得到的结果按照前面的规则进行比较<br>null与undefined是相等的<br>如果一个操作值为NaN，则相等比较返回false<br>如果两个操作值都是对象，则比较它们是不是指向同一个对象</p>
</li>
<li><p><strong>加法运算操作符:</strong><br>加法运算符在js中也用作字符串拼接，所以加法操作符的规则分为两种：<br>如果一个数是NaN，则结果就是NaN<br>如果是Infinity+Infinity，结果是Infinity<br>如果是-Infinity+(-Infinity)，结果是-Infinity<br>如果是Infinity+(-Infinity)，结果是NaN<br>如果有一个操作值是字符串，则：<br>如果两个都是字符串则，拼接起来<br>一个有一个操作值是字符串，则将另外的值转换成字符串，然后拼接起来<br>如果又一个值是对象、数值或者布尔值，则调用toString()方法取得字符串值，然后再应用前面的字符串规则。对于undefined和null，分别调用String()显式转换为字符串。</p>
</li>
<li><p><strong>逻辑操作符（!、&amp;&amp;、||）</strong><br>逻辑非（！）操作符首先通过Boolean()函数将它的操作值转换为布尔值，然后求反。<br>逻辑与（&amp;&amp;）操作符，如果一个操作值不是布尔值时，遵循以下规则进行转换：<br>如果有一个操作值为null，返回null<br>如果有一个操作值为NaN，返回NaN<br>如果有一个操作值为undefined，返回undefined<br>逻辑或（||）操作符，如果一个操作值不是布尔值，遵循以下规则：<br>如果第一个操作值经Boolean()转换后为false，则返回第二个操作值，否则返回第一个操作值（不是Boolean()转换后的值）<br>对于undefined、null和NaN的处理规则与逻辑与（&amp;&amp;）相同</p>
</li>
<li><p><strong>关系操作符（&lt;, &gt;, &lt;=, &gt;=）</strong><br>与上述操作符一样，关系操作符的操作值也可以是任意类型的，所以使用非数值类型参与比较时也需要系统进行隐式类型转换：<br>如果两个操作值都是数值，则进行数值比较<br>如果两个操作值都是字符串，则比较字符串对应的字符编码值<br>如果只有一个操作值是数值，则将另一个操作值转换为数值，进行数值比较<br>如果一个操作数是对象，则调用valueOf()方法（如果对象没有valueOf()方法则调用toString()方法），得到的结果按照前面的规则执行比较<br>如果一个操作值是布尔值，则将其转换为数值，再进行比较</p>
</li>
</ol>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/" data-id="ckq7mlsv90009dgt96jmh89rl" data-title="js数据类型及转换" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-react-hook-项目中实践" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T06:26:53.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/">react-hook 项目中实践</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h3 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h3><p>本文将介绍一些在日常开发中使用react hooks的心得体会，将着重介绍两个hooks的使用：<code>useState</code> 和 <code>useEffect</code>这两个比较常用的使用方式。</p>
<p>1、在react class组件如此成熟的时代，我们为什么还要使用react hooks呢，</p>
<p>首先我们要明确几点：</p>
<ul>
<li>react hooks完全是<strong>可选择</strong>的，你可以重写老的冗余组件，可以在新的组件使用，也可以啥都不学啥都不做，当一条咸鱼🐟。</li>
<li>100% 向后兼容 Hooks不包含任何破坏式&lt;颠覆式&gt;更新。</li>
<li>class不会被移除，依然与hooks并存，但官方更建议使用hooks，<code>因为在大部分情况下凡是class能做到的hooks都能做到</code>。</li>
</ul>
<p>在使用react class组件时，<br>2、<strong>跨组件复用含状态（state）的逻辑十分困难</strong>，因为我们不得不通过实例对象<code>this</code>上挂载的各种方法来实现业务逻辑（如setState），而过多的<code>this</code>很容易让初级开发者产生一些疑惑（诸如这个this指向谁的问题，同样的问题也发生在vue2中）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614909245017-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<p>3、<strong>复杂的组件变得冗余</strong>，在项目的后期，class组件很可能变得难以维护，试想一下，一个上千行的组件，内部会有上百个函数，由于每个函数都有自己的作用域，所以如果我们想在这些方法中使用<code>state</code> <code>props</code>的属性，我们就得不停的重定义，而hooks的functionComponent特性，让我们避免了这种事情的发生，从而减少了代码重复也提高了效率。(在不断地研究后发现其实这样做会存在一些性能问题也不好说，但是对于大部分项目而言并不太影响性能)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614909741266-image.png)</span><br><span class="line">| ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-24&#x2F;16165811241037850.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<p>4、<strong>学习成本</strong><br>这也是<code>hooks</code>的优势之一，对于掌握<code>react</code>的同学来说这简直小菜一碟，对于还没有使用<code>react</code>的同学来说也不会太难，因为<code>vue3</code>与<code>react hooks</code>从思想设计程度上是一致的。当然，<code>react</code>多年来对比<code>vue</code>，业界普遍认为<code>react</code>上手较难，所以从招聘广告来看除了知名大厂使用<code>react</code>，其他公司用<code>vue</code>会更多，而<code>hooks</code>的出现一定程度上降低了难度。</p>
<p>5、<strong>hooks将逻辑更细粒度划分</strong>，就是使用hooks不仅仅可以封装带dom的组件，也可以封装一些公用的”响应式”逻辑方法（如实时监听返回一个用户登录状态，这个状态我们可以在任何hooks组件中复用），很显然class组件在处理这类事情的时候，写法稍微复杂一些。</p>
<h3 id="useState与useEffect"><a href="#useState与useEffect" class="headerlink" title="useState与useEffect"></a>useState与useEffect</h3><p>我们先简单介绍一下 <code>useState</code>与<code>useEffect</code> 是如何使用的 </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [demo1Name, setDemo1Name] = useState(<span class="string">&#x27;&#x27;</span>);</span><br></pre></td></tr></table></figure>
<p>返回一个两项数组，第一项为<code>useState</code>返回的最新值，第二项可以理解为 具名化的<code>setState</code>，我们通过传 空字符串 作为 <code>useState</code> 唯一的参数来将其初始化为 空字符串</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 声明多个 state 变量</span></span><br><span class="line"><span class="keyword">const</span> [age, setAge] = useState(<span class="number">42</span>);</span><br><span class="line"><span class="keyword">const</span> [fruit, setFruit] = useState(<span class="string">&#x27;banana&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> [todos, setTodos] = useState([&#123; <span class="attr">text</span>: <span class="string">&#x27;学习 Hook&#x27;</span> &#125;]);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>提示<br>如果你熟悉 <code>React class</code> 的生命周期函数，你可以把 <code>useEffect Hook</code> 看做 <code>componentDidMount</code>，<code>componentDidUpdate</code> 和 <code>componentWillUnmount</code> 这三个函数的组合。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 相当于每次都会触发 componentDidUpdate</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我一直在触发useEffect1&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只有组件初始化的时候触发 componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我初始化的时候触发了useEffect2&#x27;</span>)</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只要nameZyy变化了,以及初始化时就触发 类似于 vue中的 watch但比watch强大</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;因为nameZyy变化了，我触发了useEffect3&#x27;</span>)</span><br><span class="line">    &#125;, [nameZyy])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只要nameXyb变化了,以及初始化时就触发</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;因为nameXyb变化了，我触发了useEffect4&#x27;</span>)</span><br><span class="line">    &#125;, [nameXyb])</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 组件销毁时触发return 中的函数 componentWillUnmount</span></span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 清除定时器、清除事件监听函数</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, [])</span><br></pre></td></tr></table></figure>
<p><img src="https://assets.che300.com/wiki/2021-03-05/1614932915835-image.png"></p>
<h3 id="每次组件更新相当于重新执行组件function"><a href="#每次组件更新相当于重新执行组件function" class="headerlink" title="每次组件更新相当于重新执行组件function"></a>每次组件更新相当于重新执行组件<code>function</code></h3><blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<ul>
<li><p>在<code>class</code>组件中，触发更新视图操作往往只需执行<code>render</code>函数以及特定<code>update</code>生命周期，它内部的状态通过<code>this</code>实例指向唯一内存地址，所以保证了组件状态在更新后的统一性。</p>
</li>
<li><p>在<code>hooks</code>中，没有<code>this</code>，触发视图渲染后，需要重新执行这个组件函数，所导致的后果便是内部声明的变量会全部重新定义一遍，所以<code>hooks</code>组件借助了<code>react</code> 内部的方法让该组件从无状态变为有状态（<code>useState</code>），在<code>useState</code>内部保存着一个你初始化时定义的 变量。</p>
</li>
</ul>
<p>为了更好的论证上面的理论，我这边借鉴了 <code>网易云团队</code>给出的概念 —— 类似动画帧的概念（我们将每次触发渲染称为一帧），更容易理解<code>hooks</code>的执行机制</p>
<h4 id="每一帧定义的变量方法都是独立的，前后互不影响"><a href="#每一帧定义的变量方法都是独立的，前后互不影响" class="headerlink" title="每一帧定义的变量方法都是独立的，前后互不影响"></a>每一帧定义的变量方法都是独立的，前后互不影响</h4><p>为了解释帧的概念，这里有个定时器的例子</p>
<blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Demo2</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> [num, setNum] = useState(<span class="number">0</span>);</span><br><span class="line">    <span class="comment">// componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setNum(num + <span class="number">1</span>) <span class="comment">// num一直是0，我拿的一直是第一帧即初始化时候的值</span></span><br><span class="line">            <span class="built_in">console</span>.log(num)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;, [])</span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(num,<span class="string">&#x27;我变成了1，之后一直是1，切不会触发渲染了&#x27;</span>)</span><br><span class="line">    &#125;,[num])</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo2&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;num&#125;&lt;/p&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上方demo2是如何执行的呢，<code>首先初始化第一帧</code><br>可以模拟为下方第一帧代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Demo2_1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> num_1 = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setNum(num_1 + <span class="number">1</span>)</span><br><span class="line">            <span class="built_in">console</span>.log(num_1)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;, [])</span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(num_1,<span class="string">&#x27;我初始化的时候执行以下0，第二帧我变成了1，之后一直是1，切不会触发渲染了&#x27;</span>)</span><br><span class="line">    &#125;,[num_1])</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo2&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;num_1&#125;&lt;/p&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在demo2组件内部定义了 <code>num_1</code> 常量，两个 <code>useEffect</code> 函数，其中一个<code>useEffect</code> 只会在初始化的第一帧执行。<br>所导致的后果是：这个第一帧内部的代码就始终保持不变，即内部<code>setInterval</code>的回调函数中的变量num_1一直是0，从而导致<code>setNum</code>一直重复（0+1）  也导致了第二个<code>useEffect</code> console.log num_1 的值 只会增加到1，就不再触发渲染了。</p>
<blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<p>如果上面的例子 你觉得没有说服力，ok！我给你一个网易大v的例子</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo3 = <span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; count &#125; = props;</span><br><span class="line">    <span class="keyword">const</span> handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            alert(count);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo3&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">            &lt;button onClick=&#123;handleClick&#125;&gt;点我弹我&lt;/button&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Demo3;</span><br></pre></td></tr></table></figure>
<p>我们通过<code>props</code>将<code>count</code>传入子组件，初始值为0，每隔一秒加1，我们点击 <code>点我弹我</code>按钮，alert的count值，发现并不是页面上还在自增的值，而是等于点击的<code>那一刻</code>的值。 <strong>从而论证了每一帧的值都是 独立的，就是一个普普通通的数据而已</strong>。</p>
<ul>
<li>当然这种情况只会在 hooks中出现，若使用class组件，由于this指向同一实例，this内部属性值是持续变化的。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Demo4</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">    handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            alert(<span class="built_in">this</span>.props.count);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123;</span><br><span class="line">            count</span><br><span class="line">        &#125; = <span class="built_in">this</span>.props;</span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            &lt;Card title=<span class="string">&quot;demo4&quot;</span>&gt;</span><br><span class="line">                &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="built_in">this</span>.handleClick&#125;&gt;点我弹我<span class="number">4</span>&lt;/Button&gt;</span><br><span class="line">            &lt;/Card&gt;</span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><p>上面两个例子，通过动画帧的概念辅助理解每次触发<code>render</code>时 <code>hooks</code>函数重新定义内部变量，并且通过<code>useState</code>等方式，<code>react</code>帮我们维护了一组状态，这些状态独立于函数存放。</p>
<p>需要明确的是，我们通过<code>useState</code>解构出来的变量  作为函数中的一个常量，就是普通的数据，并不存在诸如数据绑定这样的操作来驱使 <code>DOM</code> 发生更新。在调用 hooks中的<code>setState</code> 后，<code>React</code> 将重新执行 <code>render</code> 函数，仅此而已。</p>
<h3 id="永远不要欺骗useEffect"><a href="#永远不要欺骗useEffect" class="headerlink" title="永远不要欺骗useEffect"></a>永远不要欺骗useEffect</h3><p>对于 useEffect 来说，执行的时机是完成所有的 <code>DOM</code> 变更并让浏览器渲染页面后</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo5 = <span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">        id</span><br><span class="line">    &#125; = props;</span><br><span class="line"></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(id, <span class="string">&#x27;我是demo5中的id值&#x27;</span>)</span><br><span class="line">            &#125;, <span class="number">100</span>)</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo5&quot;</span>&gt;</span><br><span class="line">            我是demo5 &#123;id&#125;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通常我们会有上面的这种需求，id是由接口动态返回的，demo5作为子组件他也要使用id请求一次其他的接口，这时，实际上我们依赖了动态的<code>id</code>，但是在子组件中这么写是无法获得最新的id值，因为子组件在<code>id</code>值发生变化的时候，就已经渲染完毕了。</p>
<p><strong>针对这种情况，我们有两种解决方案</strong><br>1、<code>useEffect</code>第二个参数的数组中加上<code>id</code>依赖，并做空保护。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (id) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(id, <span class="string">&#x27;我是demo5中的id值&#x27;</span>)</span><br><span class="line">        &#125;, <span class="number">100</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;, [id])</span><br></pre></td></tr></table></figure>
<p>2、当<code>id</code>值发生变化后，再渲染子组件。<br>但是针对 诸如 wiki 这种 文章组件不会销毁的情况，则使用<code>hooks</code>的优势就体现出来了。</p>
<h3 id="useMemo的实践"><a href="#useMemo的实践" class="headerlink" title="useMemo的实践"></a>useMemo的实践</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-29&#x2F;16170023709952396.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; Button,Card &#125; <span class="keyword">from</span> <span class="string">&#x27;antd&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> [count, setCount] = useState(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">const</span> [val, setValue] = useState(<span class="string">&#x27;朱育仪&#x27;</span>);</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我又执行了&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count * <span class="number">100</span>; i++) &#123;</span><br><span class="line">            sum += i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo6&quot;</span>&gt;</span><br><span class="line">            &lt;h4&gt;&#123;count&#125;---&#123;add()&#125;&lt;/h4&gt;</span><br><span class="line">            &#123;val&#125;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;+<span class="number">1</span>&lt;/Button&gt;</span><br><span class="line">                &lt;input value=&#123;val&#125; onChange=&#123;<span class="function"><span class="params">event</span> =&gt;</span> setValue(event.target.value)&#125; /&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行上面的demo6，我们会发现，无论我们点击<code>Button</code>或者在<code>input</code>添加值，<code>add</code>函数都会执行，然而<code>add</code>函数与<code>val</code>并无关系，这就造成了性能的损耗。所以针对这种情况我们就需要使用 <code>useMemo</code>这个 hook。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> [count, setCount] = useState(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">const</span> [val, setValue] = useState(<span class="string">&#x27;朱育仪&#x27;</span>);</span><br><span class="line">    <span class="keyword">const</span> add = useMemo(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我只有count变了，我才执行&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count * <span class="number">10</span>; i++) &#123;</span><br><span class="line">            sum += i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;, [count])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card&gt;</span><br><span class="line">            &lt;h4&gt;&#123;count&#125;-&#123;add&#125;&lt;/h4&gt;</span><br><span class="line">            &#123;val&#125;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;+c1&lt;/Button&gt;</span><br><span class="line">                &lt;input value=&#123;val&#125; onChange=&#123;<span class="function"><span class="params">e</span> =&gt;</span> setValue(e.target.value)&#125; /&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时只有当我们点击 <code>Button</code> 时再触发 <code>add</code> 函数，节省了性能的消耗。<br>这里有一张题库项目中的实践图</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614936725891-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>
<p>这里将列表筛选项进行了缓存，减少了不必要的渲染，从而提高性能。（原先的class组件其实没有考虑到这种问题）</p>
<p>在过去的<code>class</code>组件中，我们通过<code> shouldComponentUpdate</code> 判断当前属性和状态是否和上一次的相同，来避免组件不必要的更新。其中的比较是对于本组件的所有属性和状态而言的，无法根据 <code>shouldComponentUpdate</code> 的返回值来使该组件一部分 <code>elements</code> 更新，另一部分不更新。（公司所有的进件系统筛选项都有这个问题）<br>而函数组件中的 <code>useMemo</code> 其实就可以代替这一部分工作。</p>
<h3 id="强大的自定义hooks"><a href="#强大的自定义hooks" class="headerlink" title="强大的自定义hooks"></a>强大的自定义hooks</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; useEffect, useState, &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">useOnline</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> [online, setOnline] = useState(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setOnline(<span class="function"><span class="params">c</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> !c</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;, <span class="number">3000</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">clearInterval</span>(timer)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> online</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的hooks 比较特殊，它定义了一个 online状态，每三秒变化一次true false  来模拟用户在线或者离线。我们可以直接返回 该状态。<br>如何使用呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> online = useOnline();</span><br><span class="line">    <span class="built_in">console</span>.log(online)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo8&quot;</span>&gt;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &#123;online ? <span class="string">&#x27;我在线&#x27;</span> : <span class="string">&#x27;我离线&#x27;</span>&#125;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该示例中直接调用 <code>const online = useOnline();</code> ,即可获取到<code>online</code>的响应数据。<br>这就是自定义<code>hooks</code>的强大之处，聪明的开发者们也正是因为自定义<code>hooks</code>的存在，开发出了各种各样好用的<code>hooks</code></p>
<h3 id="关于父组件如何调取子组件方法"><a href="#关于父组件如何调取子组件方法" class="headerlink" title="关于父组件如何调取子组件方法"></a>关于父组件如何调取子组件方法</h3><p>使用<code>useRef useImperativeHandle forwardRef</code>配合使用达到<code>class</code>组件的效果</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">interface useRefTypes &#123;</span><br><span class="line">    getTopicList: <span class="function">() =&gt;</span> <span class="keyword">void</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> topicRef = useRef&lt;useRefTypes&gt;(<span class="literal">null</span>);</span><br><span class="line">...</span><br><span class="line"><span class="keyword">const</span> topicDom = (</span><br><span class="line">     &lt;div className=&#123;styles.describeContainer&#125;&gt;</span><br><span class="line">          &lt;Topic</span><br><span class="line">               dispatch=&#123;dispatch&#125;</span><br><span class="line">               subjectId=&#123;id&#125;</span><br><span class="line">               loading=&#123;loading&#125;</span><br><span class="line">               userId=&#123;_id&#125;</span><br><span class="line">               ref=&#123;topicRef&#125;</span><br><span class="line">          /&gt;</span><br><span class="line">     &lt;/div&gt;</span><br><span class="line">)</span><br><span class="line">...</span><br><span class="line"><span class="comment">// 提交并发布评论区</span></span><br><span class="line"><span class="keyword">const</span> submitAndTopic = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!submitValue) &#123;</span><br><span class="line">        notification.warning(&#123;</span><br><span class="line">            message: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">            description: <span class="string">&#x27;请输入你的答案&#x27;</span></span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    confirm(&#123;</span><br><span class="line">        title: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">        content: <span class="string">&#x27;是否将答案同步到评论区？&#x27;</span>,</span><br><span class="line">        okText: <span class="string">&#x27;确定&#x27;</span>,</span><br><span class="line">        cancelText: <span class="string">&#x27;取消&#x27;</span>,</span><br><span class="line">        onOk: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            submit();</span><br><span class="line">            dispatch(&#123;</span><br><span class="line">                type: <span class="string">&#x27;subjectDetails/addTopic&#x27;</span>,</span><br><span class="line">                payload: &#123;</span><br><span class="line">                    subjectId: id,</span><br><span class="line">                    content: submitValue,</span><br><span class="line">                    parentTopicId: <span class="string">&#x27;topTopic&#x27;</span></span><br><span class="line">                &#125;,</span><br><span class="line">                callback: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                    <span class="keyword">if</span> (topicRef &amp;&amp; topicRef.current) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (topicRef.current.getTopicList) &#123;</span><br><span class="line">                            topicRef.current.getTopicList();</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在父组件中使用<code>usRef</code>（上方代码）<br>在子组件中使用<code>useImperativeHandle forwardRef</code>（下方代码）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将方法包裹在forwardRef中</span></span><br><span class="line"><span class="keyword">const</span> Topic: React.FC&lt;propsType&gt; = forwardRef(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> &#123;</span><br><span class="line">...</span><br><span class="line">    useImperativeHandle(ref, <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">        getTopicList</span><br><span class="line">    &#125;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>将方法包裹在 <code>forwardRef</code> 中，内部调用 <code>useImperativeHandle</code> （<code>useImperativeHandle</code> 可以让你在使用 <code>ref</code> 时自定义暴露给父组件的实例值。在大多数情况下，应当避免使用 <code>ref</code> 这样的命令式代码。<code>useImperativeHandle</code> 应当与 <code>forwardRef</code> 一起使用。）</p>
<h3 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h3><p><a target="_blank" rel="noopener" href="https://react.docschina.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render">好学的艺宝在会前讨论中和我谈到的问题如下</a></p>
<h4 id="1、Hooks-会因为在渲染时创建函数而变慢吗？"><a href="#1、Hooks-会因为在渲染时创建函数而变慢吗？" class="headerlink" title="1、Hooks 会因为在渲染时创建函数而变慢吗？"></a>1、Hooks 会因为在渲染时创建函数而变慢吗？</h4><p>不会。在现代浏览器中，闭包和类的原始性能只有在极端场景下才会有明显的差别。<br>除此之外，可以认为 Hooks 的设计在某些方面更加高效：</p>
<ul>
<li><code>Hooks</code> 避免了 <code>class</code> 需要的额外开支，像是创建类实例和在构造函数中绑定事件处理器的成本。</li>
<li>符合语言习惯的代码在使用 <code>Hooks</code> 时不需要很深的组件树嵌套。这个现象在使用高阶组件、render props、和 context 的代码库中非常普遍。组件树小了，React 的<code>工作量</code>也随之减少。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614938038176-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614927889461-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>
<p>我们将 只会在<code>useEffect</code>中执行的代码放置于<code>useEffect</code>回调函数内部，这样只有依赖值发生变化的时候才会执行<code>useEffect</code>内部函数声明。</p>
<h4 id="2、-只在最顶层使用-Hook-？"><a href="#2、-只在最顶层使用-Hook-？" class="headerlink" title="2、**只在最顶层使用 Hook**？"></a>2、**只在最顶层使用 <code>Hook</code>**？</h4><p>是的没错！！！<br>不要在<strong>循环</strong>，<strong>条件或嵌套函数</strong>中调用 <code>Hook</code>， 确保总是在你的 <code>React</code> 函数的最顶层调用他们。遵守这条规则，你就能确保 <code>Hook</code> 在每一次渲染中都按照同样的顺序被调用。这让 <code>React</code> 能够在多次的 <code>useState</code> 和 <code>useEffect</code> 调用之间保持 <code>hook</code> 状态的正确。</p>
<h3 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h3><p><a target="_blank" rel="noopener" href="https://react.docschina.org/docs/hooks-overview.html">react官方中文网</a><br><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904165500518414">https://juejin.cn/post/6844904165500518414</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_44753552/article/details/108329228">https://blog.csdn.net/qq_44753552/article/details/108329228</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/56975681">useCallback</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/412c874c5add">useEffect和useLayoutEffect的区别</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_39702483/article/details/110561916">addeventlistener事件参数_函数式编程看React Hooks(二)事件绑定副作用深度剖析</a><br><a target="_blank" rel="noopener" href="https://overreacted.io/zh-hans/why-do-hooks-rely-on-call-order/#%E7%BC%BA%E9%99%B7-2-%E5%91%BD%E5%90%8D%E5%86%B2%E7%AA%81">为什么顺序调用对 React Hooks 很重要？</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000023669309">vue3 watchEffect</a></p>
<p>3、异步回调中多次触发render问题<br><a target="_blank" rel="noopener" href="https://github.com/facebook/react/issues/18725">https://github.com/facebook/react/issues/18725</a></p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-17&#x2F;1615948305846-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/" data-id="ckq7mlsw1000qdgt92kud8uk0" data-title="react-hook 项目中实践" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-数字签名" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T06:22:18.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/">数字签名</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="数字签名的实现"><a href="#数字签名的实现" class="headerlink" title="数字签名的实现"></a>数字签名的实现</h2><h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><p>监听鼠标按下事件，鼠标移动事件，鼠标放开事件<br>鼠标按下：标志绘画开始，isDraw=true,记录当前的坐标<br>鼠标移动：如果isDraw=true，开始绘画，连接开始点和结束点画一条直线，然后标记结束点为开始点，重复绘画过程<br>鼠标放开or超出绘画区域：绘画结束<br><a target="_blank" rel="noopener" href="https://www.runoob.com/w3cnote/html5-canvas-intro.html">canvas基础</a> 、 <a target="_blank" rel="noopener" href="https://www.cnblogs.com/huaan011/p/5651806.html">beginPath和closePath</a> </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset&#x3D;&quot;utf-8&quot;&gt;</span><br><span class="line">    &lt;title&gt;数字签名&lt;&#x2F;title&gt;</span><br><span class="line">&lt;&#x2F;head&gt;</span><br><span class="line">&lt;style&gt;</span><br><span class="line">    body &#123;</span><br><span class="line">        display: flex;</span><br><span class="line">        justify-content: center;</span><br><span class="line">    &#125;</span><br><span class="line">    .header &#123;</span><br><span class="line">        display: flex;</span><br><span class="line">        justify-content: space-between;</span><br><span class="line">    &#125;</span><br><span class="line">    .canvas &#123;</span><br><span class="line">        &#x2F;* width: 600px;</span><br><span class="line">        height:300px; *&#x2F;</span><br><span class="line">        margin-top: 20px;</span><br><span class="line">        border: 1px solid #ddd;</span><br><span class="line">    &#125;</span><br><span class="line">    .image &#123;</span><br><span class="line">        border: 1px solid #ddd;</span><br><span class="line">    &#125;</span><br><span class="line">&lt;&#x2F;style&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div class&#x3D;&quot;container&quot;&gt;</span><br><span class="line">        &lt;div class&#x3D;&quot;header&quot;&gt;</span><br><span class="line">            &lt;span class&#x3D;&quot;title&quot;&gt;数字签名&lt;&#x2F;span&gt;</span><br><span class="line">            &lt;div class&#x3D;&quot;buttons&quot;&gt;</span><br><span class="line">                &lt;button class&#x3D;&quot;save&quot;&gt;保存&lt;&#x2F;button&gt;</span><br><span class="line">                &lt;button class&#x3D;&quot;reset&quot;&gt;重置&lt;&#x2F;button&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;!-- 一定要设置canvas的宽高，只是通过css设置宽高是不行的会产生偏移 --&gt;</span><br><span class="line">            &lt;canvas class&#x3D;&quot;canvas&quot;  width&#x3D;&quot;600&quot;  height&#x3D; &quot;300&quot;&gt;&lt;&#x2F;canvas&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;p&gt;保存的图片为：&lt;&#x2F;p&gt;</span><br><span class="line">            &lt;img class&#x3D;&quot;image&quot;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">    &lt;&#x2F;div&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var save &#x3D; document.querySelector(&#39;.save&#39;);</span><br><span class="line">        var reset &#x3D; document.querySelector(&#39;.reset&#39;)</span><br><span class="line">        var image &#x3D; document.querySelector(&#39;.image&#39;)</span><br><span class="line">        var canvas &#x3D; document.querySelector(&#39;.canvas&#39;)</span><br><span class="line">        var canvasContext &#x3D; canvas.getContext(&#39;2d&#39;)</span><br><span class="line">        var isDraw &#x3D; false; &#x2F;&#x2F; 标志是否要绘画</span><br><span class="line">        var startPos &#x3D; &#123;x: 0,y:0&#125; &#x2F;&#x2F; 开始坐标</span><br><span class="line">        canvasContext.strokeStyle &#x3D; &#39;#000&#39; &#x2F;&#x2F; 设置画笔颜色</span><br><span class="line">        canvasContext.lineWidth &#x3D; 1; &#x2F;&#x2F; 设置画笔的粗细</span><br><span class="line">        canvas.onmousedown &#x3D; function(ev)&#123; </span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            &#x2F;&#x2F; 开始画</span><br><span class="line">            canvasContext.beginPath();</span><br><span class="line">            isDraw &#x3D; true;</span><br><span class="line">            startPos &#x3D; &#123;</span><br><span class="line">                x: ev.offsetX,</span><br><span class="line">                y: ev.offsetY</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        canvas.onmousemove &#x3D; function(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            if(isDraw)&#123;</span><br><span class="line">                &#x2F;&#x2F; canvas中的绘制方法（如stroke,fill），都会以“上一次beginPath”之后的所有路径为基础进行绘制</span><br><span class="line">                canvasContext.beginPath(); &#x2F;&#x2F; 新建一条path</span><br><span class="line">                canvasContext.moveTo(startPos.x,startPos.y) &#x2F;&#x2F; 把画笔移动到指定的坐标</span><br><span class="line">                canvasContext.lineTo(ev.offsetX,ev.offsetY); &#x2F;&#x2F;绘制一条从当前位置到指定坐标的直线.</span><br><span class="line">                canvasContext.stroke();&#x2F;&#x2F;绘制路径</span><br><span class="line">                canvasContext.closePath() &#x2F;&#x2F; 闭合路径</span><br><span class="line">                startPos.x &#x3D; ev.offsetX;</span><br><span class="line">                startPos.y &#x3D; ev.offsetY</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        canvas.onmouseup &#x3D; function(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            isDraw &#x3D; false;</span><br><span class="line">            startPos &#x3D; &#123;x: 0,y:0&#125;</span><br><span class="line">        &#125;</span><br><span class="line">        canvas.onmouseout &#x3D; function(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            isDraw &#x3D; false;</span><br><span class="line">            canvasContext.closePath()</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 保存成图片</span><br><span class="line">        save.onclick &#x3D; function()&#123;</span><br><span class="line">            console.log(canvas)</span><br><span class="line">            var dataUrl &#x3D; canvas.toDataURL()</span><br><span class="line">            console.log(dataUrl)</span><br><span class="line">            image.src &#x3D; dataUrl;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 重置</span><br><span class="line">        reset.onclick&#x3D; function()&#123;</span><br><span class="line">            canvasContext.clearRect(0,0,canvas.width,canvas.height)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &lt;&#x2F;script&gt;</span><br><span class="line">&lt;&#x2F;body&gt;</span><br><span class="line"></span><br><span class="line">&lt;&#x2F;html&gt;</span><br></pre></td></tr></table></figure>
<p><img src="https://fe.che300.com/easymock/upload/2020/03/02/41ee2941ed6455459dbfdfa526a39a4a.png"><br>功能虽然实现了，但是这里有个问题，那就是画的线有锯齿<br><strong>原因</strong>：<br>mousemove是隔一段时间采集一个点，而lienTo()就是两点之间的连线，多个线段之间连接就会出现锯齿状<br><img src="https://fe.che300.com/easymock/upload/2020/03/02/7414cbfdceae95f6052ab5729ef3f252.png"></p>
<p><strong>解决：</strong><br>使用二次贝塞尔曲线<br>quadraticCurveTo(控制点.X, 控制点.Y, 终点.X,终点的.Y)<br><img src="https://fe.che300.com/easymock/upload/2020/03/02/833f4ee1ce9fe7a273aad114f7903653.png"><br>从上图可以看出如果要使用二倍贝塞尔曲线，至少需要三个点，而现在只有两个点（开始点和结束点），那么如何设置开始点、控制点、结束点呢？如下所示：<br>现在有A、B、C三个点，计算出B和C点的中点B1作为结束点，B点作为控制点，A点作为开始点，<br><img src="https://fe.che300.com/easymock/upload/2020/03/02/9bd0576949c8affb90a994c0a8147762.png"></p>
<p>以B1作为开始点， C为控制点，计算C和D的中点C1作为结束点<img src="https://fe.che300.com/easymock/upload/2020/03/02/4595137ebbed32c68a4a17e7f991f0d4.png"></p>
<p>重复上面的步骤就会形成一条曲线<br><img src="https://fe.che300.com/easymock/upload/2020/03/02/d0eb57fb482da0efbeed67d7d074ca27.png"></p>
<p><strong>具体实现：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset&#x3D;&quot;utf-8&quot;&gt;</span><br><span class="line">    &lt;title&gt;数字签名&lt;&#x2F;title&gt;</span><br><span class="line">&lt;&#x2F;head&gt;</span><br><span class="line">&lt;style&gt;</span><br><span class="line">    body &#123;</span><br><span class="line">        display: flex;</span><br><span class="line">        justify-content: center;</span><br><span class="line">    &#125;</span><br><span class="line">    .header &#123;</span><br><span class="line">        display: flex;</span><br><span class="line">        justify-content: space-between;</span><br><span class="line">    &#125;</span><br><span class="line">    .canvas &#123;</span><br><span class="line">        &#x2F;* width: 600px;</span><br><span class="line">        height:300px; *&#x2F;</span><br><span class="line">        margin-top: 20px;</span><br><span class="line">        border: 1px solid #ddd;</span><br><span class="line">    &#125;</span><br><span class="line">    .image &#123;</span><br><span class="line">        border: 1px solid #ddd;</span><br><span class="line">    &#125;</span><br><span class="line">&lt;&#x2F;style&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div class&#x3D;&quot;container&quot;&gt;</span><br><span class="line">        &lt;div class&#x3D;&quot;header&quot;&gt;</span><br><span class="line">            &lt;span class&#x3D;&quot;title&quot;&gt;数字签名&lt;&#x2F;span&gt;</span><br><span class="line">            &lt;div class&#x3D;&quot;buttons&quot;&gt;</span><br><span class="line">                &lt;button class&#x3D;&quot;save&quot;&gt;保存&lt;&#x2F;button&gt;</span><br><span class="line">                &lt;button class&#x3D;&quot;reset&quot;&gt;重置&lt;&#x2F;button&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;!-- 一定要设置canvas的宽高，只是通过css设置宽高是不行的会产生偏移 --&gt;</span><br><span class="line">            &lt;canvas class&#x3D;&quot;canvas&quot;  width&#x3D;&quot;600&quot;  height&#x3D; &quot;300&quot;&gt;&lt;&#x2F;canvas&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;p&gt;保存的图片为：&lt;&#x2F;p&gt;</span><br><span class="line">            &lt;img class&#x3D;&quot;image&quot;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">    &lt;&#x2F;div&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var save &#x3D; document.querySelector(&#39;.save&#39;);</span><br><span class="line">        var reset &#x3D; document.querySelector(&#39;.reset&#39;)</span><br><span class="line">        var image &#x3D; document.querySelector(&#39;.image&#39;)</span><br><span class="line">        var canvas &#x3D; document.querySelector(&#39;.canvas&#39;)</span><br><span class="line">        var canvasContext &#x3D; canvas.getContext(&#39;2d&#39;)</span><br><span class="line">        var isDraw &#x3D; false;</span><br><span class="line">        var startPos &#x3D; &#123;x: 0,y:0&#125;</span><br><span class="line">        var posArray &#x3D;[];</span><br><span class="line">        canvasContext.strokeStyle &#x3D; &#39;#000&#39;</span><br><span class="line">        canvasContext.lineWidth &#x3D; 1;</span><br><span class="line">        canvasContext.lineJoin &#x3D; &#39;round&#39;;</span><br><span class="line">        canvasContext.lineCap &#x3D; &#39;round&#39;;</span><br><span class="line">        </span><br><span class="line">        canvas.onmousedown &#x3D; function(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            isDraw &#x3D; true;</span><br><span class="line">            startPos &#x3D; &#123;</span><br><span class="line">                x: ev.offsetX,</span><br><span class="line">                y: ev.offsetY</span><br><span class="line">            &#125;</span><br><span class="line">            posArray.push(startPos)</span><br><span class="line">        &#125;</span><br><span class="line">        canvas.onmousemove &#x3D; function(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            if(!isDraw)&#123;</span><br><span class="line">                return;</span><br><span class="line">            &#125;</span><br><span class="line">            var obj &#x3D; &#123;</span><br><span class="line">                x: ev.offsetX,</span><br><span class="line">                y: ev.offsetY</span><br><span class="line">            &#125;</span><br><span class="line">            posArray.push(obj)</span><br><span class="line">            if(posArray.length &gt; 3)&#123;</span><br><span class="line">                var lastTwoPoint &#x3D; posArray.slice(-2);</span><br><span class="line">                var controlPoint &#x3D; lastTwoPoint[0];</span><br><span class="line">                var endPoint &#x3D; &#123;</span><br><span class="line">                    x: (lastTwoPoint[0].x + lastTwoPoint[1].x)&#x2F;2,</span><br><span class="line">                    y: (lastTwoPoint[0].y + lastTwoPoint[1].y)&#x2F;2</span><br><span class="line">                &#125;</span><br><span class="line">                drawLine(startPos, controlPoint, endPoint)</span><br><span class="line">                startPos &#x3D; endPoint;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        canvas.onmouseup &#x3D; closeDraw;</span><br><span class="line">        canvas.onmouseout &#x3D; closeDraw;</span><br><span class="line">        function closeDraw(ev)&#123;</span><br><span class="line">            ev.preventDefault();</span><br><span class="line">            isDraw &#x3D; false;</span><br><span class="line">            var obj &#x3D; &#123;</span><br><span class="line">                x: ev.offsetX,</span><br><span class="line">                y: ev.offsetY</span><br><span class="line">            &#125;</span><br><span class="line">            posArray.push(obj)</span><br><span class="line">            if (posArray.length &gt; 3) &#123;</span><br><span class="line">                const lastTwoPoints &#x3D; posArray.slice(-2);</span><br><span class="line">                const controlPoint &#x3D; lastTwoPoints[0];</span><br><span class="line">                const endPoint &#x3D; lastTwoPoints[1];</span><br><span class="line">                drawLine(startPos, controlPoint, endPoint);</span><br><span class="line">            &#125;</span><br><span class="line">            &#x2F;&#x2F; canvasContext.closePath()</span><br><span class="line">            posArray &#x3D; [];</span><br><span class="line">            startPos &#x3D; null;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 保存成图片</span><br><span class="line">        save.onclick &#x3D; function()&#123;</span><br><span class="line">            console.log(canvas)</span><br><span class="line">            var dataUrl &#x3D; canvas.toDataURL()</span><br><span class="line">            console.log(dataUrl)</span><br><span class="line">            image.src &#x3D; dataUrl;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 重置</span><br><span class="line">        reset.onclick&#x3D; function()&#123;</span><br><span class="line">            canvasContext.clearRect(0,0,canvas.width,canvas.height)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        function drawLine(startPoint,controlPoint,endPoint)&#123;</span><br><span class="line">             &#x2F;&#x2F; 开始画</span><br><span class="line">            canvasContext.beginPath();</span><br><span class="line">            canvasContext.moveTo(startPoint.x,startPoint.y)</span><br><span class="line">            canvasContext.quadraticCurveTo(controlPoint.x,controlPoint.y,endPoint.x,endPoint.y);</span><br><span class="line">            canvasContext.stroke();</span><br><span class="line">            canvasContext.closePath();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &lt;&#x2F;script&gt;</span><br><span class="line">&lt;&#x2F;body&gt;</span><br><span class="line"></span><br><span class="line">&lt;&#x2F;html&gt;</span><br></pre></td></tr></table></figure>

<p>结果对比：<br><img src="https://fe.che300.com/easymock/upload/2020/03/02/74552325c2f5154fd72713ea7f93e4ce.png"><br><img src="https://fe.che300.com/easymock/upload/2020/03/02/799df615aa8e7f1753d9f95f1815223b.png"></p>
<p>总结：<br>通过上图的对比，我们可以看到锯齿没有完全消除，但是还是优化了好多，<br>希望以后可以找到更好的方法<br>参考：<br><a target="_blank" rel="noopener" href="https://www.jb51.net/html5/641000.html">https://www.jb51.net/html5/641000.html</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/" data-id="ckq7mlsvj000jdgt91dbn1ndv" data-title="数字签名" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-sendbeacon" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/sendbeacon/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T06:19:33.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/sendbeacon/">sendbeacon</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <p>分享主题： <code>接口超时设置</code>、监控日志上报方式 <code>sendBeacon</code></p>
<h2 id="一、接口交互方式"><a href="#一、接口交互方式" class="headerlink" title="一、接口交互方式"></a>一、接口交互方式</h2><h3 id="1-1、XMLHttpRequest"><a href="#1-1、XMLHttpRequest" class="headerlink" title="1.1、XMLHttpRequest"></a>1.1、XMLHttpRequest</h3><p><code>XMLHttpRequest</code> 原生的接口交互方式</p>
<h3 id="1-2、Ajax"><a href="#1-2、Ajax" class="headerlink" title="1.2、Ajax"></a>1.2、Ajax</h3><p><code>Ajax</code> 基于 <code>XMLHttpRequest（XHR）</code> 浏览器和服务器之间的异步数据传输技术</p>
<h3 id="1-3、Axios"><a href="#1-3、Axios" class="headerlink" title="1.3、Axios"></a>1.3、Axios</h3><p><code>Axios</code> 基于 <code>Promise</code>，用于浏览器和 <code>node.js</code> 的 <code>http</code> 客户端</p>
<blockquote>
<p>支持 <code>Promise API</code>；<br>提供了一些并发请求的接口；<br>支持拦截请求和响应；<br>转换请求和响应数据；<br>可以取消请求；<br>自动转换 <code>JSON</code> 数据；<br>客户端支持防止 <code>CSRF</code>；<br>客户端支持防御 <code>XSRF</code>。</p>
</blockquote>
<h3 id="1-4、Fetch"><a href="#1-4、Fetch" class="headerlink" title="1.4、Fetch"></a>1.4、Fetch</h3><p><code>Fetch</code> 基于 <code>Promise</code> 设计的，采用了 <code>Promise</code> 对象。提供了一个 <code>JavaScript</code> 接口，用于访问和操纵 <code>HTTP</code> 管道的部分，例如请求和响应。它还提供了一个全局 <code>fetch()</code> 方法，该方法提供了一种简单，合理的方式来跨网络异步获取资源。<code>fetch</code> 没有采用 <code>XMLHttpRequest</code> 对象，所以针对浏览器兼容性，需要使用 <code>polyfill es6-promise</code>。</p>
<blockquote>
<p><code>Fetch</code> 只针对网络请求报错，对 <code>400</code>、<code>500</code> 当成是成功的请求，因此需要封装处理;<br><code>Fetch</code> 不支持 <code>abort</code>，不支持超时控制，使用 <code>setTimeout</code> 及 <code>Promise.race</code> 实现超时控制。</p>
</blockquote>
<h3 id="1-5、img"><a href="#1-5、img" class="headerlink" title="1.5、img"></a>1.5、img</h3><p><code>img</code>：<code>src</code> 注入接口 <code>url</code></p>
<h3 id="1-6、Beacon"><a href="#1-6、Beacon" class="headerlink" title="1.6、Beacon"></a>1.6、Beacon</h3><blockquote>
<p>监听页面在关闭或者刷新时 <code>beforeunload</code> 或者 页面正在被卸载前<code>unload</code> 触发；<br><code>Beacon API</code> 用于将少量数据通过 <code>post</code> 请求发送到服务器；<br><code>Beacon</code> 是非阻塞请求，不需要响应，包括接口错误时，也不会返回响应信息。</p>
</blockquote>
<p>适用于仅提交信息，且不需要得到响应信息的情况。</p>
<h2 id="二、超时设置"><a href="#二、超时设置" class="headerlink" title="二、超时设置"></a>二、超时设置</h2><p>针对超时设置，<code>XMLHttpRequest</code>、<code>Ajax</code>、<code>Axios</code> 可以添加 <code>timeout</code> 参数，而 <code>Fetch</code> 不支持 <code>abort</code>，要想进行超时设置，可采用 <code>setTimeout</code> 及 <code>Promise.race</code> 实现超时控制。</p>
<h6 id="XMLHttpRequest"><a href="#XMLHttpRequest" class="headerlink" title="XMLHttpRequest"></a>XMLHttpRequest</h6><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">xhr.timeout = <span class="number">3000</span>; <span class="comment">// 设置xhr请求的超时时间</span></span><br><span class="line">xhr.open(<span class="string">&#x27;post&#x27;</span>, <span class="string">&#x27;http://172.16.0.92/xxx&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line">xhr.ontimeout = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;请求超时:&#x27;</span>, e);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h6 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h6><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">    timeout: <span class="number">3000</span>, <span class="comment">// 设置超时时间</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h6 id="Axios"><a href="#Axios" class="headerlink" title="Axios"></a>Axios</h6><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">axios(&#123;</span><br><span class="line">    method: <span class="string">&#x27;post&#x27;</span>,</span><br><span class="line">    url: <span class="string">&#x27;/user/12345&#x27;</span>,</span><br><span class="line">    timeout: <span class="number">3000</span>, <span class="comment">// 设置超时时间</span></span><br><span class="line">    data: &#123;</span><br><span class="line">        firstName: <span class="string">&#x27;Fred&#x27;</span>,</span><br><span class="line">        lastName: <span class="string">&#x27;Flintstone&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h6 id="Fetch"><a href="#Fetch" class="headerlink" title="Fetch"></a>Fetch</h6><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>url 接口地址</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>option 配置参数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description </span>fetch 请求封装</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetchHttp</span>(<span class="params">url, option</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> newOptions = &#123;</span><br><span class="line">        headers: &#123;</span><br><span class="line">            Accept: <span class="string">&#x27;application/json&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;application/json; charset=utf-8&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        mode: <span class="string">&#x27;cors&#x27;</span>,</span><br><span class="line">        redirect: <span class="string">&#x27;follow&#x27;</span>,</span><br><span class="line">        referrer: <span class="string">&#x27;no-referrer&#x27;</span>,</span><br><span class="line">        ...option,</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> ( [<span class="string">&#x27;POST&#x27;</span>, <span class="string">&#x27;PUT&#x27;</span>, <span class="string">&#x27;DELETE&#x27;</span>].includes(option.method)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!(option.body <span class="keyword">instanceof</span> FormData)) &#123;</span><br><span class="line">            newOptions.body = <span class="built_in">JSON</span>.stringify(newOptions.body);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 添加超时拦截请求</span></span><br><span class="line">    <span class="keyword">let</span> controller = <span class="keyword">new</span> AbortController(),</span><br><span class="line">        signal = controller.signal,</span><br><span class="line">        <span class="comment">// 任务1：超时定时任务</span></span><br><span class="line">        timeoutPromise = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                    resolve(<span class="keyword">new</span> Response(<span class="string">&#x27;timeout&#x27;</span>, &#123; <span class="attr">status</span>: <span class="number">504</span>, <span class="attr">statusText</span>: <span class="string">&#x27;timeout &#x27;</span> &#125;));</span><br><span class="line">                    controller.abort();</span><br><span class="line">                &#125;, timeout);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 任务2：接口请求</span></span><br><span class="line">        requestPromise = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            newOptions.signal = signal;</span><br><span class="line">            <span class="keyword">return</span> fetch(url, newOptions)</span><br><span class="line">                .then(<span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (option.method === <span class="string">&#x27;DELETE&#x27;</span> || response.status === <span class="number">204</span>) &#123;</span><br><span class="line">                        <span class="keyword">return</span> response.text();</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> response.json();</span><br><span class="line">                &#125;)</span><br><span class="line">                .then(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (option.callback) &#123;</span><br><span class="line">                        option.callback(res);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> res;</span><br><span class="line">                &#125;)</span><br><span class="line">                .catch(<span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">                    <span class="built_in">console</span>.error(<span class="string">&#x27;监控接口请求出错：&#x27;</span>, error);</span><br><span class="line">                &#125;);</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 执行多个任务：等待最快对象完成</span></span><br><span class="line">    <span class="built_in">Promise</span>.race([timeoutPromise(), requestPromise()])</span><br><span class="line">        .then(<span class="function"><span class="params">resp</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(resp);</span><br><span class="line">        &#125;)</span><br><span class="line">        .catch(<span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;请求超时:&#x27;</span>, e);</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="三、sendBeacon"><a href="#三、sendBeacon" class="headerlink" title="三、sendBeacon"></a>三、sendBeacon</h2><h3 id="3-1、场景"><a href="#3-1、场景" class="headerlink" title="3.1、场景"></a>3.1、场景</h3><p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/sendBeacon">Beacon</a> 接口用于将异步和非阻塞请求发送到服务器。<code>Beacon</code> 请求使用 <code>HTTP</code> 协议中的 <code>POST</code> 方法，请求通常不需要响应。这个请求被保证在，页面的 <code>unload</code> 状态从发起到完成之前被发送。且不会产生请求阻塞，影响页面性能。</p>
<blockquote>
<p>页面埋点，监控日志上报；<br>页面/浏览器窗口在关闭前执行接口异步操作。</p>
</blockquote>
<h3 id="3-2、用法"><a href="#3-2、用法" class="headerlink" title="3.2、用法"></a>3.2、用法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">navigator.sendBeacon(url, data);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>url</code>：表示 <code>data</code> 将要被发送到的网络地址；<br><code>data</code>：将要发送的 <code>ArrayBufferView</code> 或 <code>Blob</code>, <code>DOMString</code> 或者 <code>FormData</code> 类型的数据。<br>返回值：当用户代理成功把数据加入传输队列时，<code>sendBeacon()</code> 方法将会返回 <code>true</code>，否则返回 <code>false</code>。</p>
</blockquote>
<h3 id="3-3、支持的类型"><a href="#3-3、支持的类型" class="headerlink" title="3.3、支持的类型"></a>3.3、支持的类型</h3><blockquote>
<p><code>text/plain</code>：发送普通字符串</p>
</blockquote>
<p><code>Beacon</code> 中最常用、默认的形式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">navigator.sendBeacon(url, <span class="built_in">JSON</span>.stringify(data)); <span class="comment">// await parse.json(ctx.req)</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>application/x-www-form-urlencoded</code>：发送 <code>URLSearchParams</code> 对象</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">navigator.sendBeacon(url, <span class="keyword">new</span> URLSearchParams(data)); <span class="comment">// await parse.form(ctx.req)</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>Bolb</code> 类型： 发送 <code>Bolb</code> 对象</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> blob = <span class="keyword">new</span> Blob([<span class="built_in">JSON</span>.stringify(data), &#123;</span><br><span class="line">    <span class="comment">// type: &#x27;application/json&#x27;,</span></span><br><span class="line">    type: <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>,</span><br><span class="line">&#125;]);</span><br><span class="line">navigator.sendBeacon(url, blob);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>multipart/form-data</code>：发送 <code>FormData</code> 对象</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> formData = <span class="keyword">new</span> FormData();</span><br><span class="line">formData.append(<span class="string">&#x27;text&#x27;</span>, <span class="string">&#x27;测试&#x27;</span>);</span><br><span class="line">navigator.sendBeacon(origin + <span class="string">&#x27;/api/monitor/captureData&#x27;</span>, data);</span><br></pre></td></tr></table></figure>

<h3 id="3-4、实例"><a href="#3-4、实例" class="headerlink" title="3.4、实例"></a>3.4、实例</h3><p>记录在页面上停留的时间：监听浏览器 <code>beforeunload</code> 或者 <code>unload</code></p>
<blockquote>
<p><code>beforeunload</code>：浏览器窗口关闭或者刷新；<br><code>unload</code>：页面正在被卸载。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">&#x27;beforeunload&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 测试是否支持 Beacon</span></span><br><span class="line">    <span class="keyword">if</span> (!navigator.sendBeacon) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">const</span> data = &#123;</span><br><span class="line">        start: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime(),</span><br><span class="line">        end: performance.now(),</span><br><span class="line">        url: <span class="built_in">document</span>.URL</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">const</span> url = <span class="string">&#x27;http://127.0.0.1:7071/api/monitor/demo?appKey=85f353b7c54e0f5f24152e55060f7a71&#x27;</span>;</span><br><span class="line">    navigator.sendBeacon(url, <span class="built_in">JSON</span>.stringify(data));</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="3-5、存在的问题"><a href="#3-5、存在的问题" class="headerlink" title="3.5、存在的问题"></a>3.5、存在的问题</h3><blockquote>
<ol>
<li><code>Beacon</code> 的请求方式统一为 <code>POST</code>，且不支持修改，即使 <code>method</code> 设置成 <code>GET</code> 请求，最终也是以 <code>POST</code> 发送；</li>
<li><code>POST</code> 提交数据，默认 <code>content-type</code> 是 <code>text-plain</code>。在 <code>node + eggjs</code> 服务器中获取不到对应的数据 <code>this.ctx.request.body</code> (拼接在接口地址后面的数据仍然可以使用 <code>this.ctx.request.query</code> 获取)，数据被存储在 <code>this.ctx.req</code> (返回该类型数据 <code>IncomingMessage &#123;&#125;</code>)，通过 <a target="_blank" rel="noopener" href="https://github.com/cojs/co-body">co-body</a> 解析生成需要的字段：</li>
</ol>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> parse = <span class="built_in">require</span>(<span class="string">&#x27;co-body&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> body = <span class="keyword">await</span> parse.json(<span class="built_in">this</span>.ctx.req);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>有网友表示 <code>unload</code> 事件在部分 <code>Mac Safari</code> 上会有安全警告阻止该请求，为保险起见可以在 <code>beforeunload</code> 事件中使用。</p>
</blockquote>
<h3 id="3-6、兼容性"><a href="#3-6、兼容性" class="headerlink" title="3.6、兼容性"></a>3.6、兼容性</h3><p><img src="https://fe.che300.com/easymock/upload/2020/06/18/a484bf160f147453940df248f9a2cff9.png"></p>
<h3 id="3-7、参考网址"><a href="#3-7、参考网址" class="headerlink" title="3.7、参考网址"></a>3.7、参考网址</h3><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.w3.org/TR/beacon/">w3 Beacon</a></p>
</blockquote>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://github.com/cojs/co-body">co-body</a></p>
</blockquote>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/48171879">前端日志上报新姿势 ‘Beacon’</a></p>
</blockquote>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://usefulangle.com/post/63/javascript-navigator-sendbeacon-set-form-http-header">navigator sendbeacon</a></p>
</blockquote>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/sendbeacon/" data-id="ckq7mlsvd000ddgt9ftpz9auo" data-title="sendbeacon" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-js数据类型的判断" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T05:57:40.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/">js数据类型的判断</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="JS中数据类型的判断（-typeof，instanceof，constructor，Object-prototype-toString-call"><a href="#JS中数据类型的判断（-typeof，instanceof，constructor，Object-prototype-toString-call" class="headerlink" title="JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()"></a>JS中数据类型的判断（ typeof，instanceof，constructor，Object.prototype.toString.call()</h2><h3 id="（1）typeof"><a href="#（1）typeof" class="headerlink" title="（1）typeof"></a>（1）typeof</h3><p>typeof 对于原始类型来说，除了 null 都可以显示正确的类型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="number">2</span>);               <span class="comment">// number</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">true</span>);            <span class="comment">// boolean</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="string">&#x27;str&#x27;</span>);           <span class="comment">// string</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> []);              <span class="comment">// object     []数组的数据类型在 typeof 中被解释为 object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;);    <span class="comment">// function</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> &#123;&#125;);              <span class="comment">// object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">undefined</span>);       <span class="comment">// undefined</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> <span class="literal">null</span>);            <span class="comment">// object     null 的数据类型被 typeof 解释为 object</span></span><br></pre></td></tr></table></figure>
<p>typeof 对于对象来说，除了函数都会显示 <code>object</code>，所以说 <code>typeof</code>并不能准确判断变量到底是什么类型,所以想判断一个对象的正确类型，这时候可以考虑使用 <code>instanceof</code></p>
<h3 id="（2）instanceof"><a href="#（2）instanceof" class="headerlink" title="（2）instanceof"></a>（2）instanceof</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">2</span> <span class="keyword">instanceof</span> <span class="built_in">Number</span>);                    <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="literal">true</span> <span class="keyword">instanceof</span> <span class="built_in">Boolean</span>);                <span class="comment">// false </span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;str&#x27;</span> <span class="keyword">instanceof</span> <span class="built_in">String</span>);                <span class="comment">// false  </span></span><br><span class="line"><span class="built_in">console</span>.log([] <span class="keyword">instanceof</span> <span class="built_in">Array</span>);                    <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125; <span class="keyword">instanceof</span> <span class="built_in">Function</span>);       <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(&#123;&#125; <span class="keyword">instanceof</span> <span class="built_in">Object</span>);                   <span class="comment">// true    </span></span><br><span class="line"><span class="comment">// console.log(undefined instanceof Undefined);      // error</span></span><br><span class="line"><span class="comment">// console.log(null instanceof Null);                // error</span></span><br></pre></td></tr></table></figure>
<p>可以看出直接的字面量值判断数据类型，<code>instanceof</code>可以精准判断引用数据类型<code>（Array，Function，Object）</code>，而基本数据类型不能被<code>instanceof</code>精准判断。</p>
<p>我们来看一下 <code>instanceof</code> 在MDN中的解释：<code>instanceof</code> 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 <code>prototype</code> 属性。其意思就是判断对象是否是某一数据类型（如<code>Array</code>）的实例，请重点关注一下是判断一个对象是否是数据类型的实例。在这里字面量值，2， <code>true</code> ，’<code>str</code>‘不是实例，所以判断值为false。</p>
<h3 id="（3）constructor"><a href="#（3）constructor" class="headerlink" title="（3）constructor"></a>（3）constructor</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log((<span class="number">2</span>).constructor === <span class="built_in">Number</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="literal">true</span>).constructor === <span class="built_in">Boolean</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="string">&#x27;str&#x27;</span>).constructor === <span class="built_in">String</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(([]).constructor === <span class="built_in">Array</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;).constructor === <span class="built_in">Function</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log((&#123;&#125;).constructor === <span class="built_in">Object</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>这里有一个坑，如果我创建一个对象，更改它的原型，constructor就会变得不可靠了</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Fn</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">Fn.prototype=<span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line"><span class="keyword">var</span> f=<span class="keyword">new</span> Fn();</span><br><span class="line"><span class="built_in">console</span>.log(f.constructor===Fn);    <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(f.constructor===<span class="built_in">Array</span>); <span class="comment">// true </span></span><br></pre></td></tr></table></figure>

<h3 id="（4）Object-prototype-toString-call"><a href="#（4）Object-prototype-toString-call" class="headerlink" title="（4）Object.prototype.toString.call()"></a>（4）Object.prototype.toString.call()</h3><p>使用 Object 对象的原型方法 toString ，使用 call 进行狸猫换太子，借用Object的 toString 方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="built_in">Object</span>.prototype.toString;</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="number">2</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">true</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="string">&#x27;str&#x27;</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call([]));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(&#123;&#125;));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">undefined</span>));</span><br><span class="line"><span class="built_in">console</span>.log(a.call(<span class="literal">null</span>));</span><br></pre></td></tr></table></figure>
<p>执行结果：<img src="https://fe.che300.com/easymock/upload/2020/07/17/5b12b0ac91cde488668330585c1ef71c.png"></p>
<blockquote>
<p>其实 null 不是对象，虽然 typeof null 会输出 object，但是这只是 JS 存在的一个悠久 Bug。在 JS 的最初版本中使用的是 32 位系统，为了性能考虑使用低位存储变量的类型信息，000 开头代表是对象，然而 null 表示为全零，所以将它错误的判断为 object 。虽然现在的内部类型判断代码已经改变了，但是对于这个 Bug 却是一直流传下来。</p>
</blockquote>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/" data-id="ckq7mlsva000adgt9gaql8nq6" data-title="js数据类型的判断" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-脱敏" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/%E8%84%B1%E6%95%8F/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T05:48:10.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/%E8%84%B1%E6%95%8F/">脱敏</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h2><p>全栈项目需要用到脱敏的地方</p>
<h2 id="使用介绍"><a href="#使用介绍" class="headerlink" title="使用介绍"></a>使用介绍</h2><ul>
<li>v1.0 只能匹配数字，satr和end代表需要隐藏的起始位置（satr=1,end=5  =&gt; a****aaaaaaa）<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 替换字符串中的某几位（如：18351800598 --&gt; 183****0598）(朱育仪手笔20190726)</span></span><br><span class="line"><span class="comment"> * @param  &#123;Number&#125;         [start=0]     [脱敏字符串起始位置]</span></span><br><span class="line"><span class="comment"> * @param  &#123;Number&#125;         [end=0]       [脱敏字符串终止位置]</span></span><br><span class="line"><span class="comment"> * @param  &#123;String&#125;         [str=&#x27;&#x27;]      [脱敏字符串]</span></span><br><span class="line"><span class="comment"> * @return &#123;String&#125;         [symbol=&#x27;*&#x27;]  [处理成功后的脱敏字符串]</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> replaceStrByChar = <span class="function">(<span class="params">start = <span class="number">0</span>, end = <span class="number">0</span>, str = <span class="string">&#x27;&#x27;</span>, symbol = <span class="string">&#x27;*&#x27;</span></span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 尾部长度 如：183****0598中的 0598</span></span><br><span class="line">    <span class="keyword">let</span> tailLength = str.length - end;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 切割长度 如：183****0598中的 ****</span></span><br><span class="line">    <span class="keyword">let</span> inciseLength = end - start;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断传参是否合法</span></span><br><span class="line">    <span class="keyword">if</span> (tailLength &lt; <span class="number">0</span> || inciseLength &lt; <span class="number">0</span> || start &lt; <span class="number">0</span> || end &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正则语句 如：/(\d&#123;3&#125;)\d&#123;4&#125;(\d&#123;4&#125;)/</span></span><br><span class="line">    <span class="keyword">let</span> regex = <span class="keyword">new</span> <span class="built_in">RegExp</span>(</span><br><span class="line">        <span class="string">&#x27;(\\d&#123;&#x27;</span> + start + <span class="string">&#x27;&#125;)\\d&#123;&#x27;</span> + inciseLength + <span class="string">&#x27;&#125;(\\d&#123;&#x27;</span> + tailLength + <span class="string">&#x27;&#125;)&#x27;</span></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 循环生成 脱敏符号</span></span><br><span class="line">    <span class="keyword">let</span> mySymbol = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; inciseLength; i++) &#123;</span><br><span class="line">        mySymbol += symbol;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正则匹配</span></span><br><span class="line">    <span class="keyword">let</span> finalStr = str.replace(regex, <span class="string">&#x27;$1&#x27;</span> + mySymbol + <span class="string">&#x27;$2&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 返回值</span></span><br><span class="line">    <span class="keyword">return</span> finalStr;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></li>
</ul>
<ul>
<li>v2.0 全能匹配，satr和end代表保留字符的数量（satr=1,end=1  =&gt; a***********a）<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">desensitization</span>(<span class="params">start = <span class="number">0</span>, end = <span class="number">0</span>, str = <span class="string">&#x27;&#x27;</span>, symbol = <span class="string">&#x27;*&#x27;</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 尾部长度 如：183****0598中的 0598</span></span><br><span class="line">    <span class="keyword">let</span> tailLength = end;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 切割长度 如：183****0598中的 ****</span></span><br><span class="line">    <span class="keyword">let</span> inciseLength = str.length - (end + start);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断传参是否合法</span></span><br><span class="line">    <span class="keyword">if</span> (tailLength &lt; <span class="number">0</span> || inciseLength &lt; <span class="number">0</span> || start &lt; <span class="number">0</span> || end &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正则语句 如：/(\d&#123;3&#125;)\d&#123;4&#125;(\d&#123;4&#125;)/</span></span><br><span class="line">    <span class="keyword">let</span> regex = <span class="keyword">new</span> <span class="built_in">RegExp</span>(</span><br><span class="line">        <span class="string">&#x27;(\[\\d\\D\]&#123;&#x27;</span> + start + <span class="string">&#x27;&#125;)\[\\d\\D\]&#123;&#x27;</span> + inciseLength + <span class="string">&#x27;&#125;(\[\\d\\D\]&#123;&#x27;</span> + tailLength + <span class="string">&#x27;&#125;)&#x27;</span></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 循环生成 脱敏符号</span></span><br><span class="line">    <span class="keyword">let</span> mySymbol = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; inciseLength; i++) &#123;</span><br><span class="line">        mySymbol += symbol;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正则匹配</span></span><br><span class="line">    <span class="keyword">let</span> finalStr = str.replace(regex, <span class="string">&#x27;$1&#x27;</span> + mySymbol + <span class="string">&#x27;$2&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 返回值</span></span><br><span class="line">    <span class="keyword">return</span> finalStr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/%E8%84%B1%E6%95%8F/" data-id="ckq7mlsvo000pdgt914pr8t1o" data-title="脱敏" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-Set-Map实现数组去重" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/Set-Map%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T05:41:07.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/18/Set-Map%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/">Set Map实现数组去重</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="集合"><a href="#集合" class="headerlink" title="集合"></a>集合</h2><p><a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E9%9B%86%E5%90%88/2908117?fr=aladdin">数学中的集合</a><br>集合的三大特性：确定性、互异性、无序性</p>
<h2 id="数组去重"><a href="#数组去重" class="headerlink" title="数组去重"></a>数组去重</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr1 = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">let</span> arr2 = [&#123;<span class="attr">id</span>:<span class="number">1</span>,<span class="attr">value</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">id</span>:<span class="number">2</span>,<span class="attr">value</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">id</span>:<span class="number">3</span>,<span class="attr">value</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">id</span>:<span class="number">3</span>,<span class="attr">value</span>:<span class="number">4</span>&#125;]</span><br><span class="line">数组去重可以考虑通过find,includes,findIndex,indexOf的方法来判断数组中是否含有某些元素</span><br></pre></td></tr></table></figure>
<p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/5f8d9db7956f">js数组去重</a></p>
<h2 id="js-中的Set数据结构"><a href="#js-中的Set数据结构" class="headerlink" title="js 中的Set数据结构"></a>js 中的Set数据结构</h2><p><strong>概念：</strong> set是ES6新增的数据结构。set数据结构使用了与有限集合相同的数学概念，应用在计算机的数据结构中，与数组类似，但成员都是唯一的，没有重复的值<br><strong>用法：</strong> </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个空的set集合</span></span><br><span class="line"><span class="keyword">const</span> emptySet = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line"><span class="comment">// 添加元素add(注意，add一次只能新增一个元素)</span></span><br><span class="line">emptySet.add(<span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log(emptySet)</span><br><span class="line"><span class="comment">// 添加多个元素</span></span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]</span><br><span class="line">arr.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;emptySet.add(item)&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(emptySet)</span><br><span class="line"><span class="comment">// 删除元素</span></span><br><span class="line">emptySet.delete(<span class="number">1</span>)  <span class="comment">//删除指定数据 返回一个布尔值</span></span><br><span class="line">emptySet.has(<span class="number">1</span>) <span class="comment">// 判断该值是否为set成员，返回一个布尔值</span></span><br><span class="line">emptySet.clear() <span class="comment">// 清除所有数据，没有返回值</span></span><br><span class="line"></span><br><span class="line">arr.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;emptySet.add(item)&#125;)</span><br><span class="line">emptySet.keys() <span class="comment">// 返回键名的遍历器</span></span><br><span class="line">emptySet.values() <span class="comment">// 返回键值的遍历器</span></span><br><span class="line">emptySet.entries() <span class="comment">// 返回键值对的遍历器</span></span><br><span class="line"><span class="comment">//可以使用forEach来调用Set数据结构的每个成员</span></span><br></pre></td></tr></table></figure>
<p><strong>使用Set来进行数组去重</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 普通数组</span><br><span class="line"><span class="keyword">let</span> arr1 = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">4</span>]</span><br><span class="line"><span class="keyword">let</span> newArr1 = <span class="built_in">Array</span>.from(<span class="keyword">new</span> <span class="built_in">Set</span>(arr1)) <span class="comment">// 由于Set集合是一个伪数组需要用Array.from转换下</span></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 数组对象去重</span><br><span class="line"><span class="keyword">let</span> arr2 = [&#123;<span class="attr">id</span>:<span class="number">1</span>, <span class="attr">value</span>: <span class="number">1</span>&#125;,&#123;<span class="attr">id</span>:<span class="number">2</span>, <span class="attr">value</span>:<span class="number">2</span>&#125;, &#123;<span class="attr">id</span>:<span class="number">3</span>, <span class="attr">value</span>:<span class="number">3</span>&#125;, &#123;<span class="attr">id</span>:<span class="number">1</span>, <span class="attr">value</span>:<span class="number">1</span>&#125;]</span><br><span class="line"><span class="comment">// 根据id进行去重</span></span><br><span class="line"><span class="keyword">let</span> setId = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line"><span class="keyword">let</span> setItem = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">arr2.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!setId.has(item.id)) &#123;</span><br><span class="line">        setId.add(item.id)</span><br><span class="line">        setItem.add(item)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="js中的Map数据结构"><a href="#js中的Map数据结构" class="headerlink" title="js中的Map数据结构"></a>js中的Map数据结构</h2><p><strong>简介：</strong><br>ES6 提供了 Map 数据结构。它类似于对象，也是键值对的集合，但是“键”的范围不限于字符串，各种类型的值（包括对象）都可以当作键。也就是说，Object 结构提供了“字符串—值”的对应，Map 结构提供了“值—值”的对应，是一种更完善的 Hash 结构实现。如果你需要“键值对”的数据结构，Map 比 Object 更合适。</p>
<p><strong>用法：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> m = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line"><span class="keyword">const</span>  o = &#123;<span class="attr">p</span>: <span class="string">&#x27;hello world&#x27;</span>&#125;</span><br><span class="line"><span class="comment">// 添加成员</span></span><br><span class="line">m.size() <span class="comment">// map集合的长度length</span></span><br><span class="line">m.set(o, <span class="string">&#x27;content&#x27;</span>) <span class="comment">// 对象当作键</span></span><br><span class="line">m.get(o)</span><br><span class="line">m.has(o) <span class="comment">// true</span></span><br><span class="line">m.delete(o)</span><br><span class="line">m.clear() <span class="comment">// 删除所有键值对</span></span><br><span class="line">m.keys() <span class="comment">// 所有的键集合</span></span><br><span class="line">m.values() <span class="comment">// 所有的值得集合</span></span><br><span class="line">m.entries() <span class="comment">// 所有的键值对得集合</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Map可以接收一个数组作为参数</span></span><br><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;张三&#x27;</span>],[<span class="string">&#x27;title&#x27;</span>,<span class="string">&#x27;author&#x27;</span>]])</span><br><span class="line">map.size <span class="comment">// ?</span></span><br><span class="line">map.get(<span class="string">&#x27;name&#x27;</span>) <span class="comment">// ?</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 接收数组作为参数的过程</span></span><br><span class="line"><span class="keyword">const</span> items = [</span><br><span class="line">  [<span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;张三&#x27;</span>],</span><br><span class="line">  [<span class="string">&#x27;title&#x27;</span>, <span class="string">&#x27;Author&#x27;</span>]</span><br><span class="line">];</span><br><span class="line"><span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line">items.forEach(</span><br><span class="line">  ([key, value]) =&gt; map.set(key, value)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="comment">// Map数组去重</span></span><br><span class="line"><span class="keyword">let</span> arr2 = [&#123;<span class="attr">id</span>:<span class="number">1</span>, <span class="attr">value</span>: <span class="number">1</span>&#125;,&#123;<span class="attr">id</span>:<span class="number">2</span>, <span class="attr">value</span>:<span class="number">2</span>&#125;, &#123;<span class="attr">id</span>:<span class="number">3</span>, <span class="attr">value</span>:<span class="number">3</span>&#125;, &#123;<span class="attr">id</span>:<span class="number">1</span>, <span class="attr">value</span>:<span class="number">2</span>&#125;]</span><br><span class="line"><span class="comment">// 根据数组项进行去重</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">unique</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">    <span class="keyword">return</span> arr.filter( <span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> !map.has(<span class="built_in">JSON</span>.stringify(item)) &amp;&amp; map.set(<span class="built_in">JSON</span>.stringify(item))</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 根据数组对象中指定元素进行去重 例如id</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">unique1</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">    <span class="keyword">return</span> arr.filter( <span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> !map.has(item.id) &amp;&amp; map.set(item.id)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/Set-Map%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/" data-id="ckq7mlsv40003dgt9176fgngl" data-title="Set Map实现数组去重" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-h5通过input调用相机" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/03/h5%E9%80%9A%E8%BF%87input%E8%B0%83%E7%94%A8%E7%9B%B8%E6%9C%BA/" class="article-date">
  <time class="dt-published" datetime="2021-06-03T02:54:54.000Z" itemprop="datePublished">2021-06-03</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/06/03/h5%E9%80%9A%E8%BF%87input%E8%B0%83%E7%94%A8%E7%9B%B8%E6%9C%BA/">h5通过input调用相机</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 隐藏输入框</span><br><span class="line">&lt;input ref=<span class="string">&quot;filElem&quot;</span> type=<span class="string">&quot;file&quot;</span> accept=<span class="string">&quot;image/*&quot;</span> capture=<span class="string">&quot;camera&quot;</span> style=<span class="string">&quot;display: none; width: 100%;height:100%&quot;</span> @change=<span class="string">&quot;getFile&quot;</span>&gt;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="number">2.</span> 相机图片</span><br><span class="line">&lt;el-button icon=<span class="string">&quot;el-icon-camera-solid&quot;</span> @click=<span class="string">&quot;camera&quot;</span> /&gt;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="number">3.</span> 点击相机icon调用相机</span><br><span class="line"><span class="comment">// 调用相机</span></span><br><span class="line"><span class="function"><span class="title">camera</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 通过refs获取input，并分发点击事件，同时拍照完毕后会触发input的chang事件</span></span><br><span class="line">    <span class="built_in">this</span>.$refs.filElem.dispatchEvent(<span class="keyword">new</span> MouseEvent(<span class="string">&#x27;click&#x27;</span>))</span><br><span class="line">&#125;,</span><br><span class="line"><span class="number">4.</span> 获取图片信息</span><br><span class="line"><span class="comment">// 图片信息</span></span><br><span class="line"><span class="function"><span class="title">getFile</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> inputFile = <span class="built_in">this</span>.$refs.filElem.files[<span class="number">0</span>]</span><br><span class="line">    <span class="keyword">if</span> (inputFile) &#123;</span><br><span class="line">        <span class="comment">// 七牛上传</span></span><br><span class="line">        <span class="built_in">this</span>.QI_NIU(inputFile).then(<span class="function"><span class="params">url</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(url, <span class="string">&#x27;url&#x27;</span>)</span><br><span class="line">            <span class="comment">// 掉后台接口 识别图片</span></span><br><span class="line">            API.uploadImg(&#123; url, <span class="attr">image</span>: inputFile &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(res, <span class="string">&#x27;ressssss&#x27;</span>)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>


      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/03/h5%E9%80%9A%E8%BF%87input%E8%B0%83%E7%94%A8%E7%9B%B8%E6%9C%BA/" data-id="ckq7mlsv60005dgt99z7l1wq5" data-title="h5通过input调用相机" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-格式化时间戳" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/05/26/%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%97%B6%E9%97%B4%E6%88%B3/" class="article-date">
  <time class="dt-published" datetime="2021-05-26T02:54:41.000Z" itemprop="datePublished">2021-05-26</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/05/26/%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%97%B6%E9%97%B4%E6%88%B3/">格式化时间戳</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// time表示时间戳  preciseSecond表示是否精确到秒</span></span><br><span class="line"><span class="comment">// 注意 iphone11不支持2021-06-01格式转为时间戳，支持2021/06/01</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> formatTime = <span class="function"><span class="keyword">function</span>(<span class="params">time, preciseSecond = <span class="literal">false</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> date</span><br><span class="line">    <span class="keyword">if</span> (time) &#123;</span><br><span class="line">        date = <span class="keyword">new</span> <span class="built_in">Date</span>(time)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        date = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> Y = date.getFullYear() + <span class="string">&#x27;-&#x27;</span></span><br><span class="line">    <span class="keyword">var</span> M = (date.getMonth() + <span class="number">1</span> &lt; <span class="number">10</span> ? <span class="string">&#x27;0&#x27;</span> + (date.getMonth() + <span class="number">1</span>) : date.getMonth() + <span class="number">1</span>) + <span class="string">&#x27;-&#x27;</span></span><br><span class="line">    <span class="keyword">var</span> D = (date.getDate() &lt; <span class="number">10</span> ? <span class="string">&#x27;0&#x27;</span> + date.getDate() : date.getDate())</span><br><span class="line">    <span class="keyword">var</span> h = (date.getHours() &lt; <span class="number">10</span> ? <span class="string">&#x27;0&#x27;</span> + date.getHours() : date.getHours()) + <span class="string">&#x27;:&#x27;</span></span><br><span class="line">    <span class="keyword">var</span> m = (date.getMinutes() &lt; <span class="number">10</span> ? <span class="string">&#x27;0&#x27;</span> + date.getMinutes() : date.getMinutes()) + <span class="string">&#x27;:&#x27;</span></span><br><span class="line">    <span class="keyword">var</span> s = (date.getSeconds() &lt; <span class="number">10</span> ? <span class="string">&#x27;0&#x27;</span> + date.getSeconds() : date.getSeconds())</span><br><span class="line">    <span class="keyword">if</span> (preciseSecond) &#123;</span><br><span class="line">        <span class="keyword">return</span> Y + M + D + h + m + s</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> Y + M + D</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/05/26/%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%97%B6%E9%97%B4%E6%88%B3/" data-id="ckq7mlsvn000ndgt91oex10wi" data-title="格式化时间戳" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  
    <article id="post-事件循环eventloop" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/05/25/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AFeventloop/" class="article-date">
  <time class="dt-published" datetime="2021-05-25T08:29:43.000Z" itemprop="datePublished">2021-05-25</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="p-name article-title" href="/2021/05/25/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AFeventloop/">事件循环eventloop</a>
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h5 id="事件循环eventloop"><a href="#事件循环eventloop" class="headerlink" title="事件循环eventloop"></a>事件循环eventloop</h5><h4 id="关于javascript"><a href="#关于javascript" class="headerlink" title="关于javascript"></a>关于javascript</h4><p>javascript是一门单线程语言，在最新的HTML5中提出了Web-Worker, 但javascript是单线程这一核心扔未改变。所以一切javascript版的“多线程”都是用单线程模拟出来的，一切javascript多线程都是纸老虎</p>
<h4 id="JS为什么是单线程的"><a href="#JS为什么是单线程的" class="headerlink" title="JS为什么是单线程的"></a>JS为什么是单线程的</h4><p>最初设计JS是用来在浏览器验证表单操控DOM元素的是一门脚本语言，如果js是多线程的，那么两个线程同时对一个DOM元素进行了相互冲突的操作，那么浏览器的解析器是无法执行的。</p>
<h4 id="js为什么需要异步"><a href="#js为什么需要异步" class="headerlink" title="js为什么需要异步"></a>js为什么需要异步</h4><p>如果js中不存在异步，只能自上而下执行，如果上一行解析时间很长，那么下面的代码就会被阻塞。 对于用户而言，阻塞就以为着“卡死”，这样就导致了很差的用户体验。比如在进行ajax请求的时候如果没有返回数据后面的代码就没办法执行</p>
<h4 id="js单线程又是如何实现异步的呢"><a href="#js单线程又是如何实现异步的呢" class="headerlink" title="js单线程又是如何实现异步的呢"></a>js单线程又是如何实现异步的呢</h4><p>js中的异步以及多线程都可以理解成为一种“假象”，就拿h5的WebWorker来说，子线程有诸多限制，不能控制DOM，不能修改全局对象等等，通常只用来做计算做数据处理。<br>这些限制并没有违背我们之前的观点，所以说是“假象”。JS异步的执行机制其实就是事件循环（eventloop）,理解了eventloop机制，就理解了js异步的执行机制。</p>
<h4 id="JS的事件循环（eventloop）是怎么运作的"><a href="#JS的事件循环（eventloop）是怎么运作的" class="headerlink" title="JS的事件循环（eventloop）是怎么运作的"></a>JS的事件循环（eventloop）是怎么运作的</h4><p>事件循环、eventloop\运行机制 这三个术语其实说的是同一个东西，</p>
<ol>
<li>首先判断JS是同步还是异步，同步就进入主线程运行，异步就进入event table.</li>
<li>异步任务在event table中注册事件，当满足触发条件后，（触发条件可能是延时也可能是ajax回调），被推入event queue</li>
<li>同步任务进入主线程后一直执行，直到主线程空闲时，才会去event queue中查看是否有可执行的异步任务，如果有就推入主线程中。<br><img src="https://assets.che300.com/wiki/2021-05-08/16204594577465347.png"></li>
<li>那怎么知道主线程执行栈为空啊？js引擎存在monitoring process进程，会持续不断的检查 主线程 执行栈是否为空，一旦为空，就会去event queue那里检查是否有等待被调用的函数<h4 id="宏任务、微任务"><a href="#宏任务、微任务" class="headerlink" title="宏任务、微任务"></a>宏任务、微任务</h4></li>
</ol>
<p><strong>js微任务宏任务执行机制</strong><br>遇到宏任务，先执行宏任务，将宏任务放入eventqueue，然后在执行微任务，将微任务放入eventqueue，<br>这两个queue不是一个queue。当你往外拿的时候先从微任务里拿这个回调函数，然后再从宏任务的queue上拿宏任务的回掉函数。 </p>
<p><strong>宏任务</strong><br>| #                     | 浏览器 | Node   |<br>| ——————— | —— | —— |<br>| script整体代码块      | 是     | 是     |<br>| UI交互事件            | 是     | 是     |<br>| I/O                   | 是     | 是     |<br>| setTimeout            | 是     | 是     |<br>| setInterval           | 是     | 是     |<br>| requestAnimationFrame | 是     | 否     |<br>| setImmediate          | 否     | 是     |<br>| postMessage           | 是     | 没测试 |<br>| MessageChannel        | 是     | 没测试 |<br><strong>微任务</strong><br>| #                | 浏览器 | Node |<br>| —————- | —— | —- |<br>| process.nextTick | 否     | 是   |<br>| promise.then     | 是     | 是   |<br>| MutationObserver | 是     | 否   |<br>| Object.observe   | 是     | 是   |</p>
<h4 id="自己对于同步、异步、宏任务、微任务的理解"><a href="#自己对于同步、异步、宏任务、微任务的理解" class="headerlink" title="自己对于同步、异步、宏任务、微任务的理解"></a>自己对于同步、异步、宏任务、微任务的理解</h4><ol>
<li>先执行代码中的同步任务</li>
<li>同步代码中依次执行微任务、宏任务</li>
<li>再依次执行异步任务</li>
<li>异步任务中依次执行微任务、宏任务</li>
</ol>
<h4 id="async-await的执行顺序"><a href="#async-await的执行顺序" class="headerlink" title="async/await的执行顺序"></a>async/await的执行顺序</h4><p>async表示异步代码块<br>在async中，遇到await会阻塞后面的代码，先执行async外面的同步代码，同步代码执行完，再回到async内部，继续执行await后面的代码。以下面的代码分析</p>
<h4 id="eventloop的几个例子"><a href="#eventloop的几个例子" class="headerlink" title="eventloop的几个例子"></a>eventloop的几个例子</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> data = [];</span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    url:www.javascript.com,</span><br><span class="line">    data:data,</span><br><span class="line">    success:<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;发送成功!&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;代码执行结束&#x27;</span>);</span><br><span class="line"><span class="comment">// 执行顺序如下</span></span><br><span class="line"><span class="number">1.</span> ajax放入event table中，生成回调函数success</span><br><span class="line"><span class="number">2.</span> 执行宏任务<span class="built_in">console</span></span><br><span class="line"><span class="number">3.</span> ajax回调函数注入到event queue中</span><br><span class="line"><span class="number">4.</span> 读取event queue 中的success并执行</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;2秒到了&#x27;</span>)</span><br><span class="line">&#125;, <span class="number">2000</span>)</span><br><span class="line"><span class="number">1.</span> ajax放入event table中</span><br><span class="line"><span class="number">2.</span> <span class="number">2</span>秒后生成回调函数 <span class="built_in">console</span>.log(<span class="string">&#x27;2秒到了&#x27;</span>) 放入到event queue中</span><br><span class="line"><span class="number">3.</span> 读取event queue中回调函数并执行</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/05/25/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AFeventloop/" data-id="ckq7mlsvf000fdgt9hmiefcjr" data-title="事件循环eventloop" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
</article>



  


  <nav id="page-nav">
    
    <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="page-number" href="/page/3/">3</a><a class="extend next" rel="next" href="/page/2/">下一页 &raquo;</a>
  </nav>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">六月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/05/">五月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/">js数据类型及转换</a>
          </li>
        
          <li>
            <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/">react-hook 项目中实践</a>
          </li>
        
          <li>
            <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/">数字签名</a>
          </li>
        
          <li>
            <a href="/2021/06/18/sendbeacon/">sendbeacon</a>
          </li>
        
          <li>
            <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/">js数据类型的判断</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2021 yywei<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>